﻿using System;
using System.Linq;
using System.Collections.Generic;

using TempEmployees.DAL;
using TempEmployees.BLL.EntitiesExtensions;
using TempEmployees.BLL.Database;

namespace TempEmployees.BLL.Budgets
{
    public class DepartmentBudget
    {
        protected DepartmentsInfo m_departmentInfo;

        private List<Assignment> m_assignments;
        protected List<Assignment> Assignments
        {
            get
            {
                if (m_assignments == null)
                {
                    //query definition:
                    //from each assignment that is related to this department and active in this semester =>
                    //   select the monthly hours and the salary
                    m_assignments = (
                    from assignment in DbQuery.Database.Assignments
                    where assignment.DepartmentID == m_departmentInfo.DepartmentID &&
                          assignment.SemesterID == m_departmentInfo.SemesterID &&
                          (assignment.StatusID == (int)DbConstants.Status.Active || assignment.StatusID == (int)DbConstants.Status.Approved)
                    select assignment).ToList();
                }
                return m_assignments;
            }
        }

        protected double m_initialBudget = double.NaN;
        protected double InitialBudget
        {
            get
            {
                if (double.IsNaN(m_initialBudget)) m_initialBudget = InitialBudgetCalc.CalculateInitialBudget(m_departmentInfo);
                return m_initialBudget;
            }
        }

        public DepartmentBudget(DepartmentsInfo departmentInfo)
        {
            m_departmentInfo = departmentInfo;
        }

        public double GetInitialBudget()
        {
            return InitialBudget;
        }

        public double GetStaticBalance()
        {
            Semester semester  = ESemester.GetSemesterByID(m_departmentInfo.SemesterID);

            double sum = 0;
            Assignments.ForEach(
                (a) => sum += (new AssignmentBalance(a, semester)).GetStaticCost()
                    );
            
            return InitialBudget - sum;
        }

        public double GetCurrentBalance()
        {
            Semester semester  = ESemester.GetSemesterByID(m_departmentInfo.SemesterID);

            double sum = 0;
            Assignments.ForEach(
                (a) => sum += (new AssignmentBalance(a, semester)).GetCurrentCost()
                    );

            return InitialBudget - sum;
        }
    }
}
